package com.cd.university.common.utils;

import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * 对集合的分页工具类
 * @author 陈栋
 * @create 2021/11/8 16:36
 */
public class PageUtil {

    /**
     * 对集合进行分页
     * @param pageNum 页码
     * @param pageSize 每页有多少条数据
     * @param list 集合
     * @return 返回分页之后的集合
     */
    public static PageInfo startPage(Integer pageNum,
                                     Integer pageSize,
                                     List list) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }

        // 记录总数
        Integer count = list.size();
        // 页数
        Integer pageCount = 0;
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        // 开始索引
        int fromIndex = 0;
        // 结束索引
        int toIndex = 0;

        if (!pageNum.equals(pageCount)) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        if (toIndex > list.size()) {
            toIndex = list.size();
        }

        if (fromIndex < 0) {
            fromIndex = 0;
        }

        if (fromIndex > toIndex) {
            fromIndex = 0;
            toIndex = list.size();
        }

        List pageList = list.subList(fromIndex, toIndex);
        PageInfo pageInfo = new PageInfo(pageList);
        pageInfo.setTotal(list.size());

        return pageInfo;
    }
}
